package com.udaos.modules.field.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.tomcat.util.codec.binary.Base64;

import com.udaos.common.base.Globals;
import com.udaos.common.util.DateUtil;

/**
 * 后台图片上传工具类
 * @author 穆涛涛
 *
 */
public class ImageUtils{

    /**
     * html5页面图片批量上传
     * @param base64 base64字符数字
     * @param newWidth 图片大小 0压缩为原图尺寸
     * @param request
     * @return  
     * @Description:
     */
    public static Map<String,Object> UploadImgFileBase64(String[] base64, int newWidth,HttpServletRequest request) {
        Map<String,Object> map=new HashMap<String,Object>();
        List<String> list=new ArrayList<String>();
        try {
        	for(String sfile:base64){
        		if(sfile.indexOf("base64")==-1){
        			list.add(sfile);
        		}else{
	                FileOutputStream fs = null;
	        		String newfileName = new Date().getTime() + "." + sfile.substring(sfile.indexOf("/")+1, sfile.indexOf(";"));
	                /** 原始文件夹*/
	                String imgPath = Globals.AppUploadPath + File.separator + "field" + File.separator;
	                String tempPath =  imgPath;
	                File oldFile = new File(tempPath);
	                if (!oldFile.exists()) {
	                    oldFile.mkdirs();
	                }
	                String a=sfile.substring(sfile.indexOf(".")+1,sfile.length());
	                a=a.replaceAll(" ", "+");
	                // Base64解码
	                byte[] bytes = Base64.decodeBase64(a);
	               // byte[] bytes = decoder.decodeBuffer(base64);
	                for (int i = 0; i < bytes.length; ++i) {
	                	if (bytes[i] < 0) {// 调整异常数据
	                		bytes[i] += 256;
	                	}
	                }
	                fs = new FileOutputStream(tempPath + newfileName);
	                fs.write(bytes);
	                fs.close();
	                /** 处理源文件 ，进行压缩再放置到新的文件夹*/
	                String oldPath = Globals.AppUploadRoot +File.separator + "field" + File.separator+ newfileName;
	                list.add(oldPath);
	                
	        	}
        	}
        	map.put("status", true);
		    map.put("url", list);
        		
		} catch (Exception e) {
			    e.printStackTrace();
	            map.put("status", false);
				map.put("url", null);
		}
    
        return map;
    }
    
    
    
}  

